<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片签章工具</title>
    <script src="../js/jspdf.umd.min.js"></script>
    <script src="../js/html2canvas.min.js"></script>
    <link rel="stylesheet" href="../css/all.min.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            height: 100vh;
            background-color: #fff;
            overflow: hidden;
        }
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 10px;
            overflow: auto;
            justify-content: center;
        }
        h1 {
            display: none;
        }
        .control-panel {
            width: 200px;
            background-color: #fff;
            padding: 10px;
            box-shadow: -2px 0 5px rgba(0,0,0,0.1);
            height: 100vh;
            position: sticky;
            top: 0;
            border-left: 1px solid #e9ecef;
            overflow-y: auto;
            scrollbar-width: none;
        }
        .control-panel::-webkit-scrollbar {
            display: none;
        }
        .control-group {
            margin-bottom: 10px;
            border-radius: 5px;
            background-color: white;
            padding: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .file-upload-label {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 12px 15px;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
            border-radius: 8px;
            border: 1px dashed #c4c9d6;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 10px;
        }
        .file-upload-label:hover {
            background: linear-gradient(135deg, #e6e9f0 0%, #d4d8e1 100%);
            border-color: #a8b1c7;
        }
        .upload-icon {
            font-size: 18px;
            margin-right: 8px;
        }
        .upload-text {
            font-size: 14px;
            color: #4a5568;
            font-weight: 500;
        }
        .file-input {
            display: none;
        }
        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 15px;
            color: #a0aec0;
            text-align: center;
        }
        .empty-icon {
            font-size: 24px;
            margin-bottom: 5px;
        }
        .empty-text {
            font-size: 12px;
        }
        .primary-button {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 10px 15px;
            background: linear-gradient(135deg, #4f81ff 0%, #3a66db 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            width: 100%;
            margin-top: 10px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(74, 85, 104, 0.1);
            font-size: 14px;
        }
        .primary-button:hover {
            background: linear-gradient(135deg, #3a66db 0%, #2a56c7 100%);
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(74, 85, 104, 0.15);
        }
        .primary-button:disabled {
            background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e0 100%);
            color: #a0aec0;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .button-icon {
            margin-right: 6px;
            font-size: 16px;
        }
        .preview-container {
            max-height: 120px;
            overflow-y: auto;
            border: 1px solid #e2e8f0;
            padding: 8px;
            background: white;
            border-radius: 8px;
            min-height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        label {
            display: none;
        }
        button {
            padding: 8px 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            width: 100%;
            margin-bottom: 8px;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            font-size: 13px;
        }
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.15);
        }
        button:disabled {
            background: linear-gradient(135deg, #cccccc 0%, #dddddd 100%);
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .orientation-buttons {
            display: flex;
            gap: 5px;
            margin-bottom: 8px;
        }
        .orientation-buttons button {
            flex: 1;
            background: white;
            color: #667eea;
            border: 1px solid #667eea;
        }
        .orientation-buttons button.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
        }
        .canvas-container {
            position: relative;
            margin: 10px 0;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            border-radius: 8px;
            overflow: hidden;
        }
        #a4Canvas {
            background-color: white;
            border: 1px solid #ddd;
        }
        .stamp {
            position: absolute;
            cursor: move;
            user-select: none;
            width: 120px;
            height: 120px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .stamp img {
            max-width: 100%;
            max-height: 100%;
            pointer-events: none;
        }
        .stamp-controls {
            position: absolute;
            top: -25px;
            left: 0;
            display: flex;
            gap: 5px;
        }
        .stamp-controls button {
            padding: 2px 5px;
            font-size: 12px;
            background-color: #f44336;
            width: auto;
            border-radius: 3px;
        }
        .preview-item {
            position: relative;
            margin-bottom: 5px;
        }
        .preview-image {
            max-width: 100%;
            max-height: 80px;
            display: block;
            border-radius: 3px;
        }
        .remove-preview {
            position: absolute;
            top: 0;
            right: 0;
            background: #f44336;
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 2000;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }
        
        .modal-overlay.active {
            opacity: 1;
            visibility: visible;
        }
        
        .modal-content {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            max-width: 400px;
            width: 90%;
            transform: scale(0.9);
            transition: transform 0.3s ease;
        }
        
        .modal-overlay.active .modal-content {
            transform: scale(1);
        }
        
        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }
        
        .modal-close {
            font-size: 24px;
            color: #999;
            cursor: pointer;
            transition: color 0.2s ease;
        }
        
        .modal-close:hover {
            color: #333;
        }
        
        .modal-body {
            padding: 20px;
            font-size: 16px;
            color: #555;
            line-height: 1.6;
        }
        
        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #e9ecef;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .modal-button {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: background-color 0.2s ease, transform 0.1s ease;
        }
        
        .modal-button:hover {
            transform: translateY(-1px);
        }
        
        .modal-button-primary {
            background: linear-gradient(135deg, #4f81ff 0%, #3a66db 100%);
            color: white;
            border: none;
        }
        
        .modal-button-secondary {
            background-color: white;
            color: #667eea;
            border: 1px solid #667eea;
        }
    </style>
</head>
<body>
    <div class="main-content">
        <div class="canvas-container" id="canvasContainer">
            <canvas id="a4Canvas"></canvas>
        </div>
    </div>

    <div class="control-panel">
        <div class="control-group">
            <div class="orientation-buttons">
                <button id="portraitBtn" class="active"><i class="fa fa-file-text-o"></i> 竖向</button>
                <button id="landscapeBtn"><i class="fa fa-file-text-o fa-rotate-90"></i> 横向</button>
            </div>
            <button id="clearCanvasBtn"><i class="fa fa-trash"></i> 清除文档</button>
        </div>
        
        <div class="control-group">
            <label class="file-upload-label">
                <span class="upload-icon"><i class="fa fa-file-image-o"></i></span>
                <span class="upload-text">选择文档</span>
                <input type="file" id="documentUpload" accept="image/*" class="file-input">
            </label>
            <div class="preview-container" id="documentPreviewContainer">
                <div class="empty-state">
                    <span class="empty-icon"><i class="fa fa-file-image-o"></i></span>
                    <span class="empty-text">未选择文件</span>
                </div>
            </div>
        </div>

        <div class="control-group">
            <label class="file-upload-label">
                <span class="upload-icon"><i class="fa fa-certificate"></i></span>
                <span class="upload-text">选择印章</span>
                <input type="file" id="stampUpload" accept="image/*" class="file-input">
            </label>
            <div class="preview-container" id="stampPreviewContainer">
                <div class="empty-state">
                    <span class="empty-icon"><i class="fa fa-certificate"></i></span>
                    <span class="empty-text">未选择印章</span>
                </div>
            </div>
            <button id="addStampBtn" disabled class="primary-button">
                <span class="button-icon"><i class="fa fa-plus"></i></span>
                <span>添加印章</span>
            </button>
        </div>
        
        <div class="control-group">
            <button id="clearStampsBtn" disabled><i class="fa fa-trash"></i> 清除印章</button>
        </div>
        
        <div class="control-group">
            <button id="exportPdfBtn" disabled><i class="fa fa-download"></i> 导出PDF</button>
        </div>
    </div>

    <!-- 模态框组件 -->
    <div id="customModal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <div class="modal-title" id="modalTitle">提示</div>
                <div class="modal-close" id="modalClose">&times;</div>
            </div>
            <div class="modal-body" id="modalBody">
                这里是模态框内容
            </div>
            <div class="modal-footer">
                <button class="modal-button modal-button-primary" id="modalConfirm">确定</button>
            </div>
        </div>
    </div>

    <script>
        const { jsPDF } = window.jspdf;
        let stamps = [];
        let selectedStamp = null;
        let isDragging = false;
        let offsetX, offsetY;
        let currentOrientation = 'portrait';
        let documentImages = [];
        let stampImage = null;
        
        // 模态框元素
        const modal = document.getElementById('customModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');
        const modalClose = document.getElementById('modalClose');
        const modalConfirm = document.getElementById('modalConfirm');
        
        const A4_WIDTH_PORTRAIT = 2480;
        const A4_HEIGHT_PORTRAIT = 3508;
        const A4_WIDTH_LANDSCAPE = 3508;
        const A4_HEIGHT_LANDSCAPE = 2480;
        
        const SCALE_FACTOR = 0.2;
        
        const canvas = document.getElementById('a4Canvas');
        const ctx = canvas.getContext('2d');
        const canvasContainer = document.getElementById('canvasContainer');
        const portraitBtn = document.getElementById('portraitBtn');
        const landscapeBtn = document.getElementById('landscapeBtn');
        const addStampBtn = document.getElementById('addStampBtn');
        const exportPdfBtn = document.getElementById('exportPdfBtn');
        const clearStampsBtn = document.getElementById('clearStampsBtn');
        const clearCanvasBtn = document.getElementById('clearCanvasBtn');
        const stampUpload = document.getElementById('stampUpload');
        const documentUpload = document.getElementById('documentUpload');
        const stampPreviewContainer = document.getElementById('stampPreviewContainer');
        const documentPreviewContainer = document.getElementById('documentPreviewContainer');
        
        function init() {
            setOrientation('portrait');
            
            portraitBtn.addEventListener('click', () => setOrientation('portrait'));
            landscapeBtn.addEventListener('click', () => setOrientation('landscape'));
            addStampBtn.addEventListener('click', addStamp);
            exportPdfBtn.addEventListener('click', exportToPdf);
            clearStampsBtn.addEventListener('click', clearStamps);
            clearCanvasBtn.addEventListener('click', clearDocumentImages);
            stampUpload.addEventListener('change', handleStampUpload);
            documentUpload.addEventListener('change', handleDocumentUpload);
            
            canvas.addEventListener('mousedown', handleCanvasMouseDown);
            document.addEventListener('mousemove', handleMouseMove);
            document.addEventListener('mouseup', handleMouseUp);
            
            // 模态框事件
            modalClose.addEventListener('click', closeModal);
            modalConfirm.addEventListener('click', closeModal);
            modal.addEventListener('click', (e) => {
                if (e.target === modal) closeModal();
            });
        }
        
        // 模态框函数
        function showModal(title, message) {
            modalTitle.textContent = title;
            modalBody.textContent = message;
            modal.classList.add('active');
            document.body.style.overflow = 'hidden'; // 防止背景滚动
        }
        
        function closeModal() {
            modal.classList.remove('active');
            document.body.style.overflow = ''; // 恢复背景滚动
        }
        
        function setOrientation(orientation) {
            currentOrientation = orientation;
            
            if (orientation === 'portrait') {
                portraitBtn.classList.add('active');
                landscapeBtn.classList.remove('active');
                canvas.width = A4_WIDTH_PORTRAIT * SCALE_FACTOR;
                canvas.height = A4_HEIGHT_PORTRAIT * SCALE_FACTOR;
            } else {
                portraitBtn.classList.remove('active');
                landscapeBtn.classList.add('active');
                canvas.width = A4_WIDTH_LANDSCAPE * SCALE_FACTOR;
                canvas.height = A4_HEIGHT_LANDSCAPE * SCALE_FACTOR;
            }
            
            drawCurrentPage();
            redrawStamps();
            updateButtonStates();
        }
        
        function drawCurrentPage() {
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            if (documentImages.length > 0) {
                ctx.drawImage(documentImages[0].image, 0, 0, canvas.width, canvas.height);
            } else {
                ctx.fillStyle = '#ddd';
                ctx.font = `${20 * SCALE_FACTOR}px Arial`;
                ctx.fillText('A4 ' + (currentOrientation === 'portrait' ? '竖向' : '横向'), 10, 30);
            }
        }
        
        function handleDocumentUpload(e) {
            const file = e.target.files[0];
            if (file) {
                documentPreviewContainer.innerHTML = '';
                documentImages = [];
                
                const reader = new FileReader();
                reader.onload = function(event) {
                    const img = new Image();
                    img.onload = function() {
                        documentImages.push({
                            index: 0,
                            file: file,
                            image: img,
                            url: event.target.result
                        });
                        
                        addDocumentPreview(img, 0, event.target.result);
                        
                        drawCurrentPage();
                        updateButtonStates();
                    };
                    img.src = event.target.result;
                };
                reader.readAsDataURL(file);
            }
        }
        
        function addDocumentPreview(img, index, url) {
            const previewItem = document.createElement('div');
            previewItem.className = 'preview-item';
            
            const imgElement = document.createElement('img');
            imgElement.className = 'preview-image';
            imgElement.src = url;
            
            const removeBtn = document.createElement('button');
            removeBtn.className = 'remove-preview';
            removeBtn.innerHTML = '×';
            removeBtn.onclick = (e) => {
                e.stopPropagation();
                clearDocumentImages();
            };
            
            previewItem.appendChild(imgElement);
            previewItem.appendChild(removeBtn);
            documentPreviewContainer.appendChild(previewItem);
        }
        
        function clearDocumentImages() {
            documentImages = [];
            documentPreviewContainer.innerHTML = '';
            documentUpload.value = '';
            stamps = [];
            drawCurrentPage();
            updateButtonStates();
        }
        
        function handleStampUpload(e) {
            const file = e.target.files[0];
            if (file) {
                stampPreviewContainer.innerHTML = '';
                
                const reader = new FileReader();
                reader.onload = function(event) {
                    stampImage = new Image();
                    stampImage.onload = function() {
                        const previewItem = document.createElement('div');
                        previewItem.className = 'preview-item';
                        
                        const imgElement = document.createElement('img');
                        imgElement.className = 'preview-image';
                        imgElement.src = event.target.result;
                        
                        const removeBtn = document.createElement('button');
                        removeBtn.className = 'remove-preview';
                        removeBtn.innerHTML = '×';
                        removeBtn.onclick = () => {
                            stampImage = null;
                            stampPreviewContainer.innerHTML = '';
                            stampUpload.value = '';
                            updateButtonStates();
                        };
                        
                        previewItem.appendChild(imgElement);
                        previewItem.appendChild(removeBtn);
                        stampPreviewContainer.appendChild(previewItem);
                        
                        updateButtonStates();
                    };
                    stampImage.src = event.target.result;
                };
                reader.readAsDataURL(file);
            }
        }
        
        function updateButtonStates() {
            addStampBtn.disabled = !stampImage || documentImages.length === 0;
            exportPdfBtn.disabled = stamps.length === 0 && documentImages.length === 0;
            clearStampsBtn.disabled = stamps.length === 0;
            clearCanvasBtn.disabled = documentImages.length === 0;
        }
        
        function addStamp() {
            if (!stampImage || documentImages.length === 0) {
                showModal('提示', '请先选择文档和印章图片');
                return;
            }
            
            const stampId = 'stamp-' + Date.now();
            const stampSize = 120;
            
            const stampDiv = document.createElement('div');
            stampDiv.className = 'stamp';
            stampDiv.id = stampId;
            stampDiv.style.width = stampSize + 'px';
            stampDiv.style.height = stampSize + 'px';
            
            const left = (canvas.width - stampSize) / 2;
            const top = (canvas.height - stampSize) / 2;
            stampDiv.style.left = left + 'px';
            stampDiv.style.top = top + 'px';
            
            const img = document.createElement('img');
            img.src = stampImage.src;
            stampDiv.appendChild(img);
            
            const controlsDiv = document.createElement('div');
            controlsDiv.className = 'stamp-controls';
            
            const deleteBtn = document.createElement('button');
            deleteBtn.innerHTML = '<i class="fa fa-trash"></i> 删除';
            deleteBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                removeStamp(stampId);
            });
            
            controlsDiv.appendChild(deleteBtn);
            stampDiv.appendChild(controlsDiv);
            
            canvasContainer.appendChild(stampDiv);
            
            stamps.push({
                id: stampId,
                element: stampDiv,
                x: left,
                y: top,
                width: stampSize,
                height: stampSize,
                image: stampImage.src
            });
            
            makeDraggable(stampDiv);
            updateButtonStates();
        }
        
        function makeDraggable(element) {
            element.addEventListener('mousedown', function(e) {
                if (e.target.tagName === 'BUTTON') return;
                
                selectedStamp = element;
                isDragging = true;
                
                const rect = element.getBoundingClientRect();
                offsetX = e.clientX - rect.left;
                offsetY = e.clientY - rect.top;
                
                element.style.zIndex = '1000';
                element.style.opacity = '0.8';
                
                e.preventDefault();
            });
        }
        
        function handleCanvasMouseDown(e) {
            if (!isDragging && selectedStamp) {
                selectedStamp.style.zIndex = '1';
                selectedStamp.style.opacity = '1';
                selectedStamp = null;
            }
        }
        
        function handleMouseMove(e) {
            if (!isDragging || !selectedStamp) return;
            
            const containerRect = canvasContainer.getBoundingClientRect();
            
            let newLeft = e.clientX - containerRect.left - offsetX;
            let newTop = e.clientY - containerRect.top - offsetY;
            
            newLeft = Math.max(0, Math.min(newLeft, canvas.width - selectedStamp.offsetWidth));
            newTop = Math.max(0, Math.min(newTop, canvas.height - selectedStamp.offsetHeight));
            
            selectedStamp.style.left = newLeft + 'px';
            selectedStamp.style.top = newTop + 'px';
            
            const stamp = stamps.find(s => s.id === selectedStamp.id);
            if (stamp) {
                stamp.x = newLeft;
                stamp.y = newTop;
            }
        }
        
        function handleMouseUp() {
            if (isDragging && selectedStamp) {
                selectedStamp.style.zIndex = '1';
                selectedStamp.style.opacity = '1';
            }
            isDragging = false;
        }
        
        function removeStamp(stampId) {
            const index = stamps.findIndex(s => s.id === stampId);
            if (index !== -1) {
                stamps.splice(index, 1);
                const element = document.getElementById(stampId);
                if (element) {
                    element.remove();
                }
                updateButtonStates();
            }
        }
        
        function clearStamps() {
            stamps.forEach(stamp => {
                const element = document.getElementById(stamp.id);
                if (element) {
                    element.remove();
                }
            });
            stamps = [];
            updateButtonStates();
        }
        
        function redrawStamps() {
            stamps.forEach(stamp => {
                const element = document.getElementById(stamp.id);
                if (element) {
                    element.style.left = stamp.x + 'px';
                    element.style.top = stamp.y + 'px';
                }
            });
        }
        
        function exportToPdf() {
            if (documentImages.length === 0) {
                showModal('提示', '请先选择文档图片');
                return;
            }
            
            // 显示导出中模态框
            showModal('正在导出', '正在生成PDF文件，请稍候...');
            
            const originalFileName = documentImages[0].file.name;
            const fileParts = originalFileName.split('.');
            const extension = fileParts.pop();
            const baseName = fileParts.join('.');
            const newFileName = `${baseName}（盖章版）.pdf`;
            
            const tempContainer = document.createElement('div');
            tempContainer.style.position = 'absolute';
            tempContainer.style.left = '-9999px';
            tempContainer.style.width = canvas.width + 'px';
            tempContainer.style.height = canvas.height + 'px';
            document.body.appendChild(tempContainer);
            
            const tempCanvas = document.createElement('canvas');
            tempCanvas.width = canvas.width;
            tempCanvas.height = canvas.height;
            const tempCtx = tempCanvas.getContext('2d');
            
            if (documentImages.length > 0) {
                tempCtx.drawImage(documentImages[0].image, 0, 0, canvas.width, canvas.height);
            }
            
            stamps.forEach(stamp => {
                const img = new Image();
                img.src = stamp.image;
                tempCtx.drawImage(img, stamp.x, stamp.y, stamp.width, stamp.height);
            });
            
            tempContainer.appendChild(tempCanvas);
            
            html2canvas(tempContainer, {
                scale: 2,
                logging: false,
                useCORS: true,
                backgroundColor: null
            }).then(canvasResult => {
                closeModal(); // 关闭导出中模态框
                
                const imgData = canvasResult.toDataURL('image/png');
                
                let pdf;
                if (currentOrientation === 'portrait') {
                    pdf = new jsPDF('p', 'mm', 'a4');
                } else {
                    pdf = new jsPDF('l', 'mm', 'a4');
                }
                
                const imgWidth = pdf.internal.pageSize.getWidth();
                const imgHeight = canvasResult.height * imgWidth / canvasResult.width;
                
                pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
                pdf.save(newFileName);
                
                document.body.removeChild(tempContainer);
                
                // 显示成功模态框
                showModal('成功', 'PDF文件已成功导出！');
            }).catch(error => {
                console.error('导出PDF时出错:', error);
                closeModal(); // 关闭导出中模态框
                showModal('错误', '导出PDF失败，请重试');
            });
        }
        
        window.onload = init;
    </script>
</body>
</html>